package com.funsport.controller.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.PageResult;
import com.funsport.common.Result;
import com.funsport.entity.Event;
import com.funsport.entity.EventSignup;
import com.funsport.security.SecurityUtils;
import com.funsport.service.IEventService;
import com.funsport.service.IEventSignupService;
import com.funsport.service.IEventGroupService;

import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Tag(name = "Web管理端活动", description = "Web管理端活动管理接口")
@RestController
@RequestMapping("/web/event")
@RequiredArgsConstructor
public class WebEventController {

    private final IEventService eventService;
    private final IEventSignupService eventSignupService;
    private final IEventGroupService eventGroupService;

    @Operation(summary = "获取活动列表")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @GetMapping("/list")
    public Result<PageResult<Event>> getEventList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Page<Event> pageParam = new Page<>(page, pageSize);
        Page<Event> result = eventService.page(pageParam);
        
        return Result.success(PageResult.build(
                result.getRecords(), result.getTotal(), page, pageSize));
    }

    @Operation(summary = "删除活动")
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{id}")
    public Result<Void> deleteEvent(@PathVariable Long id) {
        eventService.removeById(id);
        return Result.success();
    }

    @Operation(summary = "获取活动参与者列表")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER', 'CLUB_ADMIN')")
    @GetMapping("/{id}/participants")
    public Result<List<EventSignup>> getEventParticipants(
            @PathVariable Long id,
            @RequestParam(required = false) String status) {
        List<EventSignup> participants = eventSignupService.getEventParticipants(id, status);
        return Result.success(participants);
    }

    @Operation(summary = "审核活动报名")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN')")
    @PostMapping("/signup/{signupId}/approve")
    public Result<Void> approveSignup(
            @PathVariable Long signupId,
            @RequestParam Boolean approved) {
        Long operatorId = SecurityUtils.getCurrentUserId();
        eventSignupService.approveSignup(signupId, approved, operatorId);
        return Result.success(approved ? "已通过申请" : "已拒绝申请", null);
    }

    @Operation(summary = "候补转正")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN')")
    @PostMapping("/{id}/promote-waitlist")
    public Result<Integer> promoteFromWaitlist(@PathVariable Long id) {
        int promotedCount = eventSignupService.promoteFromWaitlist(id);
        return Result.success(String.format("已转正%d人", promotedCount), promotedCount);
    }

    @Operation(summary = "创建活动分组", description = "活动创建者在报名结束后创建分组，自动均匀分配参与者")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN', 'USER')")
    @PostMapping("/{eventId}/groups/create")
    public Result<Void> createEventGroups(
            @PathVariable Long eventId,
            @RequestParam Integer groupCount) {
        Long creatorId = SecurityUtils.getCurrentUserId();
        boolean success = eventGroupService.createGroupsAndAssignParticipants(eventId, groupCount, creatorId);
        if (success) {
            return Result.success("分组创建成功", null);
        } else {
            return Result.error("分组创建失败");
        }
    }

    @Operation(summary = "获取活动分组信息", description = "查询活动的所有分组及成员详情")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN', 'USER')")
    @GetMapping("/{eventId}/groups")
    public Result<List<Map<String, Object>>> getEventGroups(@PathVariable Long eventId) {
        List<Map<String, Object>> groups = eventGroupService.getEventGroupsWithMembers(eventId);
        return Result.success(groups);
    }

    @Operation(summary = "删除活动分组", description = "删除活动的所有分组")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN', 'USER')")
    @DeleteMapping("/{eventId}/groups")
    public Result<Void> deleteEventGroups(@PathVariable Long eventId) {
        Long creatorId = SecurityUtils.getCurrentUserId();
        // 验证是否是创建者（在service层验证）
        boolean success = eventGroupService.deleteEventGroups(eventId);
        if (success) {
            return Result.success("分组删除成功", null);
        } else {
            return Result.error("分组删除失败");
        }
    }
}
